package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.query.RequiredPermission;
import cn.wolfcode.rbac.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service

public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private ApplicationContext ctx;

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Permission permission) {
        if(permission.getId() == null){
            permissionMapper.insert(permission);
        }else{
            permissionMapper.updateByPrimaryKey(permission);
        }
    }

    @Override
    public Permission get(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject queryObject) {
        Integer row = permissionMapper.selectForCount(queryObject);
        if(row == null){
            return PageResult.EMPTY_PAGE;
        }
        List<Permission> data = permissionMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),data,row);
    }

    @Override
    public void reload() {

        Set<String> expressions =  permissionMapper.selectExpressions();
        Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> values = beans.values();
        for (Object value : values) {

            Method[] methods = value.getClass().getMethods();

            for (Method method : methods) {
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);

                if(annotation != null&&!expressions.contains(annotation.value()[1])){

                    Permission p = new Permission();
                    p.setName(annotation.value()[0]);
                    p.setExpression(annotation.value()[1]);
                    permissionMapper.insert(p);
                }
            }
        }
    }
}
